var debug = require('debug')('apiManager');
var koa = require('koa');
//配置文件
var config = require('./config/config');

var app = koa();
app.use(function* (next){
    //config 注入中间件，方便调用配置信息
    if(!this.config){
        this.config = config;
    }
    yield next;
});




var onerror = require('koa-onerror');
onerror(app);

//post body 解析
var bodyParser = require('koa-bodyparser');
app.use(bodyParser());

//静态文件cache
var staticCache = require('koa-static-cache');
var staticDir = config.staticDir;
app.use(staticCache(staticDir+'/'));


//log记录
//var Logger = require('mini-logger');
//var logger = Logger({
//    dir: config.logDir,
//    categories: ['http'],
//    format: 'YYYY-MM-DD-[{category}][.log]'
//});

//router use : logger.error(new Error(''))
//global.logger = logger;
//控制台打印日志
app.use(require('koa-logger')());

//设置session
app.keys = ['what'];
var session = require('koa-generic-session');
//app.use(session({key:"apiManager"},app));
app.use(session());

//log http request and response
app.use(function* (next) {
    console.log(this.request.body);
    yield next;
    console.log(this.response.body);
})

//数据校验
var schema = require('koa-scheme');
app.use(schema(__dirname+"/scheme/scheme",{debug:true}));

//允许跨域请求
var cors = require('koa-cors');
app.use(cors({credentials:true,methods:"*"}));

//路由
var router = require('koa-router');
app.use(router(app));

//应用路由
var appRouter = require('./router/index');
appRouter(app);

//upload file
//app.context.saveToFile =



app.listen(config.port);
console.log('listening on port %s',config.port);

module.exports = app;


